// pages/my/index/index.js
var call = require("../../../utils/request.js");
var verification = require("../../../utils/util.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {}, // 用户信息
    getTime: '', // 获取时间

    // 改版
    pageStatus: false,
    quotaBg: '/image/my/quotaBg.png', // 账户余额背景图
    balanceStatus: true,              // 余额是否可见 
    balanceData: {},                  // 余额数据

    customerShow: false,
    phoneShow: false, // 绑定手机号
    phoneStatus: false, // 绑定手机号成功
    phone: '', // 手机号
    code: '', // 验证码
    codeStatus: false, // 获取验证码的状态
    time: 60000, // 倒计时

    userInfoService: {}, // 精品服务的用户信息
    expertShow: false, // 专家 - 认证

    // 给消息加数字提示
    page: 1,
    limit: 10,
    unreadTotal: 0, // 未读消息数
    keyName: '', // 搜索字段
    timer:null
  },
  // 去优惠券
  goCoupon () {
    wx.navigateTo({
      url: '/pages/my/coupon/index/index',
    })
  },
  // 去园区
  goPark(){
    wx.navigateTo({
      url: '/pages/park/index/index',
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getUserinfo() // 获取精品服务用户数据
    //this.getListData()  // 获取消息数据
    this.setData({ currentPark: wx.getStorageSync('currentPark') })
    this.getUnread()
    this.setTimer()
  },
  getUnread(){
    wx.cloud.callContainer({
      "config": {
        "env": "prod-0g38oh8hf0e4d5ac"
      },
      "path": "/v1/chat/unReadNum",
      "header": {
        "X-WX-SERVICE": "springboot-069k"
      },
      "method": "get",
      "data": {
        "action": "inc"
      }
    }).then(res => {
      console.log(res.data, '定时器');
      if(res.data.code==1){
        // if (res.data.data > 0) {
          this.setData({
            'unreadTotal': res.data.data
          })
        // }
      }else{
        if (this.data.timer) {
          console.log('卸载定时器');
          clearInterval(this.data.timer);
          this.setData({
            timer: null
          })
        }
      }
    })
  },
  setTimer(){
    let _this = this
    let timer = setInterval(_this.getUnread, 5000)
    this.setData({
      timer
    })
  },
  onHide: function () {
    console.log('隐藏');
    if (this.data.timer) {
      console.log('卸载定时器');
      clearInterval(this.data.timer);
      this.setData({
        timer: null
      })
    }
  },
  onUnload: function () {
    console.log('卸载');
    if (this.data.timer) {
      console.log('卸载定时器');
      clearInterval(this.data.timer);
      this.setData({
        timer: null
      })
    }
  },
  // 获取消息数据
  getListData (status) {
    let page = this.data.page // 当前页
    let limit = this.data.limit // 每页条数
    let keyName = this.data.keyName // 搜索
    call.httpData('GET','/api/user/maillist',{ page,limit,keyName },
    (res) => {
      console.log(res,'获取消息数据')
      if(res.code == 1){
        let unreadTotal = res.data.unreadTotal
        this.setData({unreadTotal})
      }else{
        wx.showToast({ icon: 'none',title: res.msg })
      }
    },() => {
      doFail();
    })
  },
  // 获取精品服务用户数据
  getUserinfo () {
    call.httpData('POST','/api/user/userinfo', {},
    res => {
      console.log(res,'获取用户信息')
      if(res.code == 1){
        let Data = res.data
        this.setData({userInfoService: Data})
        // if(Data.isSeeMobile == false){this.setData({ phoneShow: true })}
      }else{
        wx.showToast({ icon: 'none',title: res.msg });
      }
      this.setData({ pageStatus: true })
    },function (err) {
      console.log(err)
    })
  },


  // 账户余额状态切换
  balanceStatusChange () {
    this.setData({ balanceStatus: !this.data.balanceStatus })
  },
  // 去账户余额
  goBalance () {
    wx.navigateTo({
      url: '/pages/balance/index/index'
    })
  },
  onLoad: function (options) {
    let quotaBg = wx.getFileSystemManager().readFileSync(this.data.quotaBg, 'base64');  //背景图转义
    let userInfo = wx.getStorageSync('userInfo');
    console.log(userInfo)
    this.setData({
      userInfo: userInfo,
      getTime: this.getTimeState(),
      quotaBg: 'data:image/jpg;base64,' + quotaBg,
    })

    this.balance(); // 获取余额



    let menuButtonObject = wx.getMenuButtonBoundingClientRect();
    wx.getSystemInfo({
      success: res => {
        let statusBarHeight = res.statusBarHeight // 状态栏的高度
        let navTop = menuButtonObject.top * 2
        let navObjWid = res.windowWidth - menuButtonObject.right + menuButtonObject.width // 胶囊按钮与右侧的距离 = windowWidth - right+胶囊宽度
        let navHeight = statusBarHeight + menuButtonObject.height + (menuButtonObject.top - statusBarHeight) * 2;
        let capsuleHeight = menuButtonObject.height * 2; //胶囊高度
        console.log(`导航栏总体高度${navHeight},胶囊距离顶部距离${navTop}.height,胶囊宽度(包括右边距离)${navObjWid}`)
        console.log(menuButtonObject)
        let contentHeight = capsuleHeight + navTop + 6 // 中间内容高度
        this.setData({
          navHeight,navTop,capsuleHeight,contentHeight
        })
      },
      fail(err) {
        console.log(err);
      }
    })
  },
  // 去已收藏商品
  goCollection(){
    wx.navigateTo({
      url: '/subPackages/pages/standard/my/collection/index/index',
    })
  },
  // 去订单选择
  goOrderChoice () {
    wx.navigateTo({
      url: '/pages/order/choice/index',
    })
  },
  // 去支付密码
  goPassword () {
    wx.navigateTo({
      url: '/pages/my/password/index/index',
    })
  },
  // 去我的地址
  goAddress(){
    wx.navigateTo({
      url: '/subPackages/pages/standard/my/address/index/index',
    })
  },
  // 关闭员工认证
  onExpertClose(){
    this.setData({ expertShow: false })
  },
  // 去员工认证
  goExpert(){
    let { is_attestation } = this.data.userInfoService
    if(is_attestation == 0){
      wx.navigateTo({
        url: '/subPackages/pages/standard/my/expert/index/index',
      })
    }else{
      this.setData({ expertShow: true })
    }
  },
  // 获取余额
  balance () {
    call.getData('/api/user/balance', {}, res => {
      if(res.code == 1){
        console.log(res,'获取余额')
        this.setData({ balanceData: res.data })
      }else{
        wx.showToast({ icon: 'none',title: res.msg })
      }
      this.setData({ pageStatus: true })
    }, err => {
      console.log(err)
    })
  },
  // 绑定手机号打开
  onPhoneOpen () {
    this.setData({ phoneShow: true })
  },
  // 绑定手机号关闭
  onPhoneClose () {
    this.setData({ phoneShow: false })
    setTimeout(res=>{
      this.setData({ phoneStatus: false })
    },1000)
  },
  // 获取验证码
  onVerificationCode () {
    let mobile = this.data.phone
    if(verification.isPhoneNumber(mobile)){
      call.httpData('POST','/api/user/getcode', { mobile },
      res => {
        console.log(res,'获取验证码')
        if(res.code == 1){
          this.setData({ codeStatus: true })
        }else{
          wx.showToast({ icon: 'none',title: res.msg });
        }
      },function (err) {
        console.log(err)
      })
    }else{
      wx.showToast({ icon: 'none',title: '手机号错误'});
    }
  },
  // 验证码倒计时后执行
  finished () {
    this.setData({ codeStatus: false })
  },
  // 不再提醒
  clickbindmobile () {
    call.httpData('POST','/api/user/clickbindmobile', {},
    res => {
      console.log(res,'不再提醒')
      if(res.code == 1){
        let userInfo = this.data.userInfo
        userInfo.isSeeMobile = true
        this.setData({ userInfo,phoneShow: false })
      }else{
        wx.showToast({ icon: 'none',title: res.msg });
      }
    },function (err) {
      console.log(err)
    })
  }, 
  // 立即绑定
  binding () {
    let mobile = this.data.phone
    let code = this.data.code
    if(verification.isPhoneNumber(mobile)){
      call.httpData('POST','/api/user/bindmobile', { mobile,code },
      res => {
        console.log(res,'立即绑定')
        if(res.code == 1){
          this.setData({ phone: '',code: '',phoneStatus: true,codeStatus: false })
        }else{
          wx.showToast({ icon: 'none',title: res.msg });
        }
      },function (err) {
        console.log(err)
      })
    }else{
      wx.showToast({ icon: 'none',title: '手机号错误'});
    }
  },
  // 我的订单
  order () {
    wx.navigateTo({
      url: '/pages/order/index/index'
    })
  },
  // 切换商家端
  goBusiness () {
    //wx.setStorageSync('role','business') // user 是用户 business 是商家
    wx.reLaunch({ url: '/subPackages/pages/business/home/index/index' })
  },
  // 发票管理
  invoice () {
    wx.navigateTo({
      url: '/pages/invoice/index/index'
    })
  },
  // 首页
  goHome () {
    wx.redirectTo({
      url: '/pages/home/index'
    })
  },
  // 工作
  goWork () {
    wx.redirectTo({
      url: '/pages/work/index/index'
    })
  },
  // 生活
  goLife () {
    wx.redirectTo({
      url: '/subPackages/pages/standard/home/index/index'
    })
  },
  // 消息
  goNew () {
    let userInfo = wx.getStorageSync('userInfo')  // 用户信息
    if(JSON.stringify(userInfo) == "{}"){
      let isSignIn = this.selectComponent('#isSignIn'); // 页面获取自定义组件实例
      isSignIn.isLogin(); // 通过实例调用组件事件
    }else{
      wx.redirectTo({
        url: '/pages/news/index/index'
      })
    }
  },
  // 卡包
  card () {
    wx.navigateTo({
      url: '/pages/card/index'
    })
  },
  // 个人资料
  personalData () {
    wx.navigateTo({
      url: '/pages/my/personalData/index/index'
    })
    // wx.navigateTo({
    //   url: '/pages/my/personalData/index'
    // })
  },
  // 联系我们
  goContactUs(){
    wx.navigateTo({
      url: '/pages/my/contactUs/index/index'
    })
  },
  // 关于我们
  about () {
    wx.navigateTo({
      url: '/pages/my/about/index'
    })
  },
  // 未开放功能
  Public () {
    wx.showToast({
      icon: 'none',
      title: '加紧施工中...',
    })
  },
  // 拨打电话 
  Telephone () {
    wx.makePhoneCall({
      phoneNumber: '02865199199' //仅为示例，并非真实的电话号码
    })
  },
  // 付款码
  paymentCode () {
    wx.navigateTo({
      url: '/pages/paymentCode/balance/index'
    })
  },
  // 获取时间
  getTimeState () {
    // 获取当前时间
    let timeNow = new Date();
    // 获取当前小时
    let hours = timeNow.getHours();
    // 设置默认文字
    let text = ``;
    // 判断当前时间段
    if (hours >= 7 && hours < 9) {
        text = `早上好`;
    } else if (hours >= 9 && hours < 11) {
        text = `上午好`;
    }else if (hours >= 11 && hours < 13) {
        text = `中午好`;
    } else if (hours >= 13 && hours < 18) {
        text = `下午好`;
    } else if (hours >= 18 && hours < 24) {
        text = `晚上好`;
    } else if (hours >= 0 && hours < 7) {
        text = `凌晨好`;
    }
    // 返回当前时间段对应的状态
    console.log(hours)
    return text;
  },
})